<template>
  <div class="fee-management">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="支付者类型" prop="payerType">
            <el-select v-model="searchForm.payerType" placeholder="请选择支付者类型" clearable>
              <el-option
                v-for="item in payerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付者ID" prop="payerId">
            <el-input v-model="searchForm.payerId" placeholder="请输入支付者ID"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">新增费用</el-button>
            <el-button type="warning" @click="handleExport">导出Excel</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="payerType" label="支付者类型" width="120">
          <template slot-scope="scope">
            {{ scope.row.payerType === 0 ? '单位' : '求职者' }}
          </template>
        </el-table-column>
        <el-table-column prop="payerId" label="支付者ID" width="120"></el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentDate" label="支付日期" width="120">
          <template slot-scope="scope">
            {{ scope.row.paymentDate }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              @click="handleConfirm(scope.row)"
              :disabled="scope.row.status !== 0">确认</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDiscard(scope.row)"
              :disabled="scope.row.status !== 0">废弃</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 新增费用对话框 -->
      <el-dialog :title="'新增费用'" :visible.sync="dialogVisible" width="500px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="支付者类型" prop="payerType">
            <el-select v-model="form.payerType" placeholder="请选择支付者类型">
              <el-option
                v-for="item in payerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付者ID" prop="payerId">
            <el-input v-model="form.payerId" placeholder="请输入支付者ID"></el-input>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input-number v-model="form.amount" :precision="2" :step="0.01" :min="0"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'FeeManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        payerType: null,
        payerId: null
      },
      payerTypeOptions: [
        { value: 0, label: '单位' },
        { value: 1, label: '求职者' }
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      form: {
        payerType: null,
        payerId: '',
        amount: 0
      },
      rules: {
        payerType: [{ required: true, message: '请选择支付者类型', trigger: 'change' }],
        payerId: [{ required: true, message: '请输入支付者ID', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const response = await this.$http.post('/fee-management/page', {
          current: this.currentPage,
          size: this.pageSize,
          ...this.searchForm
        })
        if (response.data.code === 200) {
          this.tableData = response.data.data.records
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取费用列表失败')
        }
      } catch (error) {
        console.error('获取费用列表失败:', error)
        this.$message.error('获取费用列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.resetFields()
      })
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const response = await this.$http.post('/fee-management/add', this.form)
            if (response.data.code === 200) {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(response.data.msg || '添加失败')
            }
          } catch (error) {
            console.error('添加失败:', error)
            this.$message.error('添加失败')
          }
        }
      })
    },
    async handleConfirm(row) {
      try {
        await this.$confirm('确认该费用项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.post(`/fee-management/confirm/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('确认成功')
          this.$set(row, 'status', 1)
        } else {
          this.$message.error(response.data.msg || '确认失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('确认失败:', error)
          this.$message.error('确认失败')
        }
      }
    },
    async handleDiscard(row) {
      try {
        await this.$confirm('确认废弃该费用项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.post(`/fee-management/discard/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('废弃成功')
          this.$set(row, 'status', 2)
        } else {
          this.$message.error(response.data.msg || '废弃失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('废弃失败:', error)
          this.$message.error('废弃失败')
        }
      }
    },
    async handleExport() {
      try {
        const response = await this.$http.get('/fee-management/export', {
          responseType: 'blob'
        })
        
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = '费用管理表.xlsx'
        link.click()
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        0: '未处理',
        1: '已确认',
        2: '已废弃'
      }
      return statusMap[status] || '未知'
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.fee-management {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 